﻿#include "datasourcetiles.h"
#include <QString>
#include <osgDB/WriteFile>
#include <QDebug>
#include <TileKey.h>
#include <QDir>
#include <QColor>
#include <osgDB/ReadFile>
#include <QFile>

rxtiler::DataSourceTiles::DataSourceTiles()
{
    _nodata = osg::Vec4(0,0,0,0);
}

rxtiler::DataSourceTiles::~DataSourceTiles()
{

}

//设置无背景的颜色值
void rxtiler::DataSourceTiles::setNoDataColor(osg::Vec4 color)
{
    _nodata = color;
}

//保存图片
bool rxtiler::DataSourceTiles::saveImage(rxtiler::TileKey &key, osg::Image *img)
{
    QDir _dir;
    //把int型的lod、y、x转化成QString四位，不够用0补齐
    //leftTustified,左对齐
    QString lstr = QString::number(key.lod);
    QString ystr = QString::number(key.y);
    QString xstr = QString::number(key.x);

    //创建目录，用“/”分隔
    QString str_dir = this->_path;
    str_dir += "/" + lstr;
    if(!_dir.exists(str_dir))
    {
        _dir.mkdir(str_dir);
    }

    str_dir += "/" + ystr;//2222
    if(!_dir.exists(str_dir))
    {
        _dir.mkdir(str_dir);
    }
    str_dir += "/" + xstr + this->getFileExt();//111

    //向目录里存图片
    if(!_dir.exists(str_dir))
    {
       osgDB::writeImageFile(*img,str_dir.toStdString().c_str());
    }
    else
    {
        //读取已保存的图片
        osg::Image* previous_img = osgDB::readImageFile(str_dir.toStdString().c_str());
        for(int x = 0; x <  img->s(); x ++)
        {
            for(int y = 0; y < img->t(); y++)
            {
                osg::Vec4 c1 = img->getColor(x,y);
                osg::Vec4 c2 = previous_img->getColor(x,y);
                c1 += c2;
                img->setColor(c1,x,y);
            }
        }
        //最后将融合后的照片保存
        osgDB::writeImageFile(*img,str_dir.toStdString().c_str());
    }
    return true;
}

bool rxtiler::DataSourceTiles::saveDEM(rxtiler::TileKey &key, osg::HeightField *dem)
{
    QDir _dir;
    //把int型的lod、y、x转化成QString四位，不够用0补齐
    //leftTustified,左对齐
    QString lstr = QString::number(key.lod);
    QString ystr = QString::number(key.y).rightJustified(4,'0');
    QString xstr = QString::number(key.x).rightJustified(4,'0');

    //创建目录，用“/”分隔
    QString str_dir = _path;
    str_dir += "/" + lstr;
    if(!_dir.exists(str_dir))
    {
        _dir.mkdir(str_dir);
    }

    str_dir += "/" + ystr;//2222
    if(!_dir.exists(str_dir))
    {
        _dir.mkdir(str_dir);
    }
    str_dir += "/" + ystr + "_" + xstr + ".vec";

    //向目录里存图片
    QFile file(str_dir);
    short *s_dem = (short*)malloc(60*60*sizeof(short));
    if(!_dir.exists(str_dir))
    {
        for(int x = 0; x < 60; x++ )
        {
            for( int y = 0; y < 60; y++)
            {
                s_dem[y*60+x] = (short)dem->getHeight(x,59 - y);
            }
        }
    }
    if(file.open(QIODevice::WriteOnly))
    {
        file.write((char*)s_dem,3600*2);
        file.close();
    }
    free(s_dem);
    return true;
}
